package com.wxit.eduservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wxit.commonutils.JwtUtils;
import com.wxit.commonutils.R;
import com.wxit.educenter.entity.UcenterMember;
import com.wxit.eduservice.client.UcenterClient;
import com.wxit.eduservice.entity.EduComment;
import com.wxit.eduservice.service.EduCommentService;
import com.wxit.exception.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author 吴杰
 * @since 2021-12-20
 */
@RestController
@RequestMapping("/eduservice/comment")
//@CrossOrigin
public class EduCommentController {

    @Autowired
    private EduCommentService eduCommentService;

    @Autowired
    private UcenterClient ucenterClient;

    //根据课程id查询评论列表
    @GetMapping("index/{page}/{limit}")
    public R index(@PathVariable long page, @PathVariable long limit, String courseId){
        Page<EduComment> pageParam = new Page<>(page, limit);
        QueryWrapper<EduComment> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        eduCommentService.page(pageParam,wrapper);

        List<EduComment> commentList = pageParam.getRecords();

        HashMap<String, Object> map  = new HashMap<>();
        map.put("items", commentList);
        map.put("current", pageParam.getCurrent());
        map.put("pages", pageParam.getPages());
        map.put("size", pageParam.getSize());
        map.put("total", pageParam.getTotal());
        map.put("hasNext", pageParam.hasNext());
        map.put("hasPrevious", pageParam.hasPrevious());
        return R.ok().data(map);
    }

    @PostMapping("save")
    public R save(@RequestBody EduComment eduComment, HttpServletRequest request){
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(memberId)){
            throw new GuliException(20001,"请先登录");
        }
        eduComment.setMemberId(memberId);

        UcenterMember ucenterInfo = ucenterClient.getInfo(memberId);
//        R info = ucenterClient.getInfo(memberId);
        eduComment.setNickname(ucenterInfo.getNickname());
        eduComment.setAvatar(ucenterInfo.getAvatar());

        eduCommentService.save(eduComment);
        return R.ok();
    }
}

